


using System;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using SubSonic.Linq.Structure;
using SubSonic.Query;
using SubSonic.Schema;
using System.Data.Common;
using System.Collections.Generic;


namespace Domain.Model
{
    public partial class BelDecorDB : IQuerySurface
    {

        public IDataProvider DataProvider;
        public DbQueryProvider provider;
        
        public static IDataProvider DefaultDataProvider { get; set; }

        public bool TestMode
		{
            get
			{
                return DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            }
        }

        public BelDecorDB() 
        {
            if (DefaultDataProvider == null) {
                DataProvider = ProviderFactory.GetProvider("sqlServerCS");
				DataProvider.InitializeSharedConnection(DataProvider.ConnectionString);
            }
            else {
                DataProvider = DefaultDataProvider;
            }
            Init();
        }

        public BelDecorDB(string connectionStringName)
        {
            DataProvider = ProviderFactory.GetProvider(connectionStringName);
			DataProvider.InitializeSharedConnection(DataProvider.ConnectionString);
            Init();
        }

		public BelDecorDB(string connectionString, string providerName)
        {
            DataProvider = ProviderFactory.GetProvider(connectionString,providerName);
			DataProvider.InitializeSharedConnection();
            Init();
        }

		public ITable FindByPrimaryKey(string pkName)
        {
            return DataProvider.Schema.Tables.SingleOrDefault(x => x.PrimaryKey.Name.Equals(pkName, StringComparison.InvariantCultureIgnoreCase));
        }

        public Query<T> GetQuery<T>()
        {
            return new Query<T>(provider);
        }
        
        public ITable FindTable(string tableName)
        {
            return DataProvider.FindTable(tableName);
        }
               
        public IDataProvider Provider
        {
            get { return DataProvider; }
            set {DataProvider=value;}
        }
        
        public DbQueryProvider QueryProvider
        {
            get { return provider; }
        }
        
        BatchQuery _batch = null;
        public void Queue<T>(IQueryable<T> qry)
        {
            if (_batch == null)
                _batch = new BatchQuery(Provider, QueryProvider);
            _batch.Queue(qry);
        }

        public void Queue(ISqlQuery qry)
        {
            if (_batch == null)
                _batch = new BatchQuery(Provider, QueryProvider);
            _batch.Queue(qry);
        }

        public void ExecuteTransaction(IList<DbCommand> commands)
		{
            if(!TestMode)
			{
                using(var connection = commands[0].Connection)
				{
                   if (connection.State == ConnectionState.Closed)
                        connection.Open();
                   
                   using (var trans = connection.BeginTransaction()) 
				   {
                        foreach (var cmd in commands) 
						{
                            cmd.Transaction = trans;
                            cmd.Connection = connection;
                            cmd.ExecuteNonQuery();
                        }
                        trans.Commit();
                    }
                    connection.Close();
                }
            }
        }

        public IDataReader ExecuteBatch()
        {
            if (_batch == null)
                throw new InvalidOperationException("There's nothing in the queue");
            if(!TestMode)
                return _batch.ExecuteReader();
            return null;
        }
			
        public Query<Caixa> Caixas { get; set; }
        public Query<Cliente> Clientes { get; set; }
        public Query<ContaPagar> ContaPagars { get; set; }
        public Query<ContaReceber> ContaRecebers { get; set; }
        public Query<Endereco> Enderecos { get; set; }
        public Query<Fornecedor> Fornecedors { get; set; }
        public Query<Funcionario> Funcionarios { get; set; }
        public Query<Numerador> Numeradors { get; set; }
        public Query<Pedido> Pedidos { get; set; }
        public Query<PerfilPagina> PerfilPaginas { get; set; }
        public Query<Pessoa> Pessoas { get; set; }
        public Query<Produto> Produtos { get; set; }
        public Query<ProdutoPedido> ProdutoPedidos { get; set; }
        public Query<Servico> Servicos { get; set; }
        public Query<ServicoPedido> ServicoPedidos { get; set; }
        public Query<Status> Statuses { get; set; }
        public Query<StatusPedido> StatusPedidos { get; set; }
        public Query<Telefone> Telefones { get; set; }
        public Query<TipoConta> TipoContas { get; set; }
        public Query<VwCliente> VwClientes { get; set; }
        public Query<VwContaReceber> VwContaRecebers { get; set; }
        public Query<VwContasAPagar> VwContasAPagars { get; set; }
        public Query<VwFornecedor> VwFornecedors { get; set; }
        public Query<VwFuncionario> VwFuncionarios { get; set; }
        public Query<vwPedido> vwPedidos { get; set; }
        public Query<VwProduto> VwProdutos { get; set; }
        public Query<VwProdutoPedido> VwProdutoPedidos { get; set; }
        public Query<VwServicoPedido> VwServicoPedidos { get; set; }

			

        #region ' Aggregates and SubSonic Queries '
        public Select SelectColumns(params string[] columns)
        {
            return new Select(DataProvider, columns);
        }

        public Select Select
        {
            get { return new Select(this.Provider); }
        }

        public Insert Insert
		{
            get { return new Insert(this.Provider); }
        }

        public Update<T> Update<T>() where T:new()
		{
            return new Update<T>(this.Provider);
        }

        public SqlQuery Delete<T>(Expression<Func<T,bool>> column) where T:new()
        {
            LambdaExpression lamda = column;
            SqlQuery result = new Delete<T>(this.Provider);
            result = result.From<T>();
            result.Constraints=lamda.ParseConstraints().ToList();
            return result;
        }

        public SqlQuery Max<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = DataProvider.FindTable(objectName).Name;
            return new Select(DataProvider, new Aggregate(colName, AggregateFunction.Max)).From(tableName);
        }

        public SqlQuery Min<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Min)).From(tableName);
        }

        public SqlQuery Sum<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Sum)).From(tableName);
        }

        public SqlQuery Avg<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Avg)).From(tableName);
        }

        public SqlQuery Count<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Count)).From(tableName);
        }

        public SqlQuery Variance<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.Var)).From(tableName);
        }

        public SqlQuery StandardDeviation<T>(Expression<Func<T,object>> column)
        {
            LambdaExpression lamda = column;
            string colName = lamda.ParseObjectValue();
            string objectName = typeof(T).Name;
            string tableName = this.Provider.FindTable(objectName).Name;
            return new Select(this.Provider, new Aggregate(colName, AggregateFunction.StDev)).From(tableName);
        }

        #endregion

        void Init()
        {
            provider = new DbQueryProvider(this.Provider);

            #region ' Query Defs '
            Caixas = new Query<Caixa>(provider);
            Clientes = new Query<Cliente>(provider);
            ContaPagars = new Query<ContaPagar>(provider);
            ContaRecebers = new Query<ContaReceber>(provider);
            Enderecos = new Query<Endereco>(provider);
            Fornecedors = new Query<Fornecedor>(provider);
            Funcionarios = new Query<Funcionario>(provider);
            Numeradors = new Query<Numerador>(provider);
            Pedidos = new Query<Pedido>(provider);
            PerfilPaginas = new Query<PerfilPagina>(provider);
            Pessoas = new Query<Pessoa>(provider);
            Produtos = new Query<Produto>(provider);
            ProdutoPedidos = new Query<ProdutoPedido>(provider);
            Servicos = new Query<Servico>(provider);
            ServicoPedidos = new Query<ServicoPedido>(provider);
            Statuses = new Query<Status>(provider);
            StatusPedidos = new Query<StatusPedido>(provider);
            Telefones = new Query<Telefone>(provider);
            TipoContas = new Query<TipoConta>(provider);
            VwClientes = new Query<VwCliente>(provider);
            VwContaRecebers = new Query<VwContaReceber>(provider);
            VwContasAPagars = new Query<VwContasAPagar>(provider);
            VwFornecedors = new Query<VwFornecedor>(provider);
            VwFuncionarios = new Query<VwFuncionario>(provider);
            vwPedidos = new Query<vwPedido>(provider);
            VwProdutos = new Query<VwProduto>(provider);
            VwProdutoPedidos = new Query<VwProdutoPedido>(provider);
            VwServicoPedidos = new Query<VwServicoPedido>(provider);
            #endregion


            #region ' Schemas '
        	if(DataProvider.Schema.Tables.Count == 0)
			{
            	DataProvider.Schema.Tables.Add(new CaixaTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ClienteTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ContaPagarTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ContaReceberTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new EnderecoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new FornecedorTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new FuncionarioTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new NumeradorTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new PedidoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new PerfilPaginaTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new PessoaTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ProdutoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ProdutoPedidoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ServicoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new ServicoPedidoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new StatusTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new StatusPedidoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new TelefoneTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new TipoContaTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwClienteTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwContaReceberTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwContasAPagarTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwFornecedorTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwFuncionarioTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new vwPedidosTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwProdutoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwProdutoPedidoTable(DataProvider));
            	DataProvider.Schema.Tables.Add(new VwServicoPedidoTable(DataProvider));
            }
            #endregion
        }
        

        #region ' Helpers '
            
        internal static DateTime DateTimeNowTruncatedDownToSecond() {
            var now = DateTime.Now;
            return now.AddTicks(-now.Ticks % TimeSpan.TicksPerSecond);
        }

        #endregion

    }
}